package com.zy.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zy.dao.BannerMapper;
import com.zy.model.Banner;
import com.zy.restApi.FileUploadApi;
import com.zy.restApi.IdGeneratorApi;
import com.zy.web.bean.BannerDTO;
import com.zy.web.bean.ResponseResult;
import lombok.extern.java.Log;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: shopping153_cloud
 * @description:
 * @author: zy
 * @create: 2025-08-21 08:55
 */
@Service
@Log
public class BannerServiceImpl extends ServiceImpl<BannerMapper, Banner> implements BannerService {

    @Autowired
    private RestTemplate restTemplate;    //情况一的RestTemplate测试
//    @Override
//    public BannerDTO addBanner(BannerDTO banner) {
//        //调用 idGenerator服务, 取出id号
//        //情况一的RestTemplate测试  , 注意此处的地址  , why? 因为当前product并没有在nacos上注册，所以只能直接以 ip:port 访问
//        String url = "http://localhost:8185/id/next";
//        ResponseResult responseResult = restTemplate.getForObject(url, ResponseResult.class);
//        log.info(   responseResult.toString() );
//        if(   responseResult==null ||  responseResult.getCode()!=1  ){
//            throw new RuntimeException( "调用idGenerator服务失败" );
//        }
//        Long id = (Long) responseResult.getData();
//        banner.setBannerId( id );
//
//        return banner;
//    }


//    @Override
//    public BannerDTO addBanner(BannerDTO banner) {
//        //调用 idGenerator服务, 取出id号
//        //情况一的RestTemplate测试  , 注意此处的地址  , why? 因为当前product并没有在nacos上注册，所以只能直接以 ip:port 访问
//        String url = "http://idGenerator/id/next";
//        ResponseResult responseResult = restTemplate.getForObject(url, ResponseResult.class);
//        log.info(   responseResult.toString() );
//        if(   responseResult==null ||  responseResult.getCode()!=1  ){
//            throw new RuntimeException( "调用idGenerator服务失败" );
//        }
//        Long id = (Long) responseResult.getData();
//        banner.setBannerId( id );
//
//        return banner;
//    }


    //两个服务使用不同的负载均衡策略
//    @Override
//    public BannerDTO addBanner(BannerDTO banner) {
//        //调用 idGenerator服务, 取出id号
//        //情况一的RestTemplate测试  , 注意此处的地址  , why? 因为当前product并没有在nacos上注册，所以只能直接以 ip:port 访问
//        String url = "http://idGenerator/id/next";
//        ResponseResult responseResult = restTemplate.getForObject(url, ResponseResult.class);
//        log.info(   responseResult.toString() );
//        if(   responseResult==null ||  responseResult.getCode()!=1  ){
//            throw new RuntimeException( "调用idGenerator服务失败" );
//        }
//        Long id = (Long) responseResult.getData();
//        banner.setBannerId( id );
//
//
//        String url2="http://fileUpload/upload";
//        //构建请求体
//        MultiValueMap<String,Object> body=new LinkedMultiValueMap<>( );
//        try {
//            ByteArrayResource fileResource = new ByteArrayResource(banner.getImageUrlFile().getBytes()) {
//                @Override
//                public String getFilename() {
//                    return banner.getImageUrlFile().getOriginalFilename();
//                }
//            };
//            body.add("uploadFiles", fileResource);
//        }catch(IOException ex){
//            throw new RuntimeException( ex );
//        }
//        //构建请求头
//        HttpHeaders headers=new HttpHeaders();
//        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
//        //组装请求
//        HttpEntity<MultiValueMap<String,Object>> requestEntity=new HttpEntity<>(  body, headers );
//
//        ResponseResult responseResult2 = restTemplate.postForObject(url2, requestEntity, ResponseResult.class);
//        log.info(   responseResult2.toString() );
//        if(   responseResult2==null ||  responseResult2.getCode()!=1  ){
//            throw new RuntimeException( "调用fileUpload服务失败" );
//        }
//        List<String> urls=(List<String>) responseResult2.getData();
//        banner.setImageUrl( urls.get(0) );
//        log.info( "banner的图片地址为:"+banner.getImageUrl() );
//
//
//
//        return banner;
//    }


     //方案二: 利用Feign客户端
    @Autowired
    private IdGeneratorApi idGeneratorApi;
    @Autowired
    private FileUploadApi fileUploadApi;


    @Override
    @Transactional
    public BannerDTO addBanner(BannerDTO banner) {
        ResponseResult<Long> responseResult = idGeneratorApi.getNextId();  //jdk动态代理对象
        log.info(   responseResult.toString() );
        if(   responseResult==null ||  responseResult.getCode()!=1  ){
            throw new RuntimeException( "调用idGenerator服务失败" );
        }
        Long id = responseResult.getData();
        banner.setBannerId( id );


        ResponseResult responseResult2 = this.fileUploadApi.upload( new MultipartFile[]{ banner.getImageUrlFile() });  //jdk动态代理对象


        log.info(   responseResult2.toString() );
        if(   responseResult2==null ||  responseResult2.getCode()!=1  ){
            throw new RuntimeException( "调用fileUpload服务失败" );
        }
        List<String> urls=(List<String>) responseResult2.getData();
        banner.setImageUrl( urls.get(0) );
        log.info( "banner的图片地址为:"+banner.getImageUrl() );



        //                       bannerDTO           banner Model
        Banner b= new Banner();
        b.setBannerStatus(  BannerService.BANNER_STATUS_NORMAL  );
        BeanUtils.copyProperties(    banner,    b  );

        boolean f= this.save(    b  );
        if(  !f ){
            throw new RuntimeException("添加广告轮播失败");
        }
        return banner;
    }




    /**
     * 前台: 根据状态查询banners轮播图，按照bannerId降序
     */
    @Override
    public List<BannerDTO> getBannersByStatus(Integer bannerStatus){
        LambdaQueryWrapper<Banner> queryWrapper=new LambdaQueryWrapper<>();
        if( bannerStatus!=null&& bannerStatus!=-1 ){
            queryWrapper.eq(Banner::getBannerStatus,bannerStatus);  // where bannerstatus=#bannerStatus
        }
        queryWrapper.orderByDesc(Banner::getBannerId);
        List<Banner> banners = this.list(queryWrapper);
        // 类型转换   Banner的model转为   DTO的 BannerDTO对象
        return  banners.stream().map(   bannerModel->{
            BannerDTO dto=new BannerDTO();
            BeanUtils.copyProperties(  bannerModel,   dto );
            return dto;
        } ).collect( Collectors.toList() );
    }
}
